package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.SpeechManager;

import java.util.ArrayList;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.util.Log;

 
public class DeleteContact extends BaseActivity {
	
	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.DeleteContact.SHOW";
	private static final String TAG = DeleteContact.class.getSimpleName();
		
	private SpeechManager speechManager;
	private Vibrator vibrator;
	private String position;
	private String contactNumber;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		speechManager = SpeechManager.getInstance(getApplicationContext());
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		Intent intent = getIntent();

		// Metodo di BaseViewManager
		Init(getBaseContext());
		setContentView(getBaseView());
		position = getString(R.string.TTS_Delete_Contact); 

		contactNumber = intent.getStringExtra("ResultFromPrevious");

		ArrayList<ContentProviderOperation> ops =
			new ArrayList<ContentProviderOperation>();

		ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
				.withSelection(Phone.NUMBER + "=?", new String[]{contactNumber})
				.build());

		try{
			ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
		}
		catch (RemoteException e){ 
			Log.d(TAG, "Add Contact: RemoteException " + e);// error
		}
		catch (OperationApplicationException e){
			Log.d(TAG, "Add Contact: OperationApplicationException " + e);// error
		}       

		speechManager.say(getString(R.string.TTS_Contact_Deleted), true, false);
		onClick_A();
	}
	
	// CLOSE
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");
		vibrator.vibrate(100);
		Intent intent;
		intent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		intent.putExtra("Result", "NORESULT");
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		sendBroadcast(intent);
		sentResult = true;
		finish();	
	}
	
	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		vibrator.vibrate(100);
		if(position != null)
			speechManager.say(position, false, false);	
	}
	
	// REPEAT 
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		vibrator.vibrate(100);

	}

	// BACK - DONE
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
		onClick_A();
	}
}
